﻿using Sidvall.Collections;
using Sidvall.Serialization;
using Sidvall.WorkItemManager.Net.Services.V1;

namespace Sidvall.WorkItemManager.Model
{
    public static partial class DataPortalEventManager
    {
        static partial void OnDataPortalInvoke(Sidvall.Business.IDataPortalContext context)
        {
            object item;
            int? value;

            if (context.SaveContext != null)
            {
                if (context.ResourceItems != null)
                    item = context.ResourceItems.FirstOrDefault();
                else
                    item = context.ResourceItem;
                value = Sidvall.SystemContext.Current.CodeManager.GetPropertyValue(item, Sidvall.WorkItemManager.Data.Fields.WorkerField.ServerConnectionId.ToString()).ToNullableInt32();
                ParameterManager.InitializeParameters(context.SaveContext, value);
            }
        }
        static partial void OnDataPortalInvokeComplete(Sidvall.Business.IDataPortalContext context)
        {
            ServerConnection serverConnection;

            serverConnection = ParameterManager.GetServerConnection(context.Parameters);
            if (serverConnection != null)
            {
                if (context.ResultValueList != null)
                {
                    foreach (var item in context.ResultValueList)
                        InitializeItem(serverConnection, item);
                }
                else if (context.ResultValueItem != null)
                {
                    InitializeItem(serverConnection, context.ResultValueItem);
                }
            }
        }
        private static void InitializeItem(ServerConnection serverConnection, object item)
        {
            Sidvall.SystemContext.Current.CodeManager.SetFieldValue(item, serverConnection.ServerConnectionId,
                "_" + Sidvall.WorkItemManager.Data.Fields.WorkerField.ServerConnectionId.ToString());
        }
    }
}